<template>
  <el-row>
    <el-row>
      <el-col :span="24">
        <el-col :span="20">
          <el-page-header @back="goBack" :content="title_content"></el-page-header>
        </el-col>
        <el-col :span="3">
          <el-button type="primary" size="medium" style="float: right" @click="submitForm">提交</el-button>
        </el-col>
      </el-col>
    </el-row>
    <el-divider></el-divider>
    <el-row v-loading="saveLoading">
      <el-col :span="11">
        <el-row class="uplold">
          <el-col :span="24" class="row">
            <el-card class="box-card" shadow="never">
              <div v-if="TimgList.length <= 0" style="text-align: center;font-size: 15px;color: #8c939d">暂无添加任何文件</div>
              <div slot="header" class="clearfix">
                <span>任务附件</span>
                <el-button style="float: right; padding: 3px 0" type="text" @click="allFileDown">全部下载</el-button>
              </div>
              <!--        图片-->
              <ul class="el-upload-list el-upload-list--picture-card">
                <span v-for="img in TimgList">
            <el-tooltip
              class="item"
              effect="light"
              :hide-after="2000"
              :content="img.name"
              placement="bottom-start">
            <li tabindex="0" class="el-upload-list__item is-ready"
                v-if="img.type=='jpg'|img.type=='png'|img.type=='jpeg'">
              <img class="el-upload-list__item-thumbnail" :src="img.url">
              <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="imgCheck(img.url)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span class="el-upload-list__item-delete" @click="imgDonwload(img.url)">
                    <i class="el-icon-download"></i>
                  </span>
              </span>
            </li></el-tooltip>
          </span>
              </ul>
              <!--        文件file-->
              <span class="file_card">
            <ul class="el-upload-list el-upload-list--picture-card">
              <span v-for="img in TimgList">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :hide-after="2000"
                  :content="img.name"
                  placement="bottom-start">
                <li tabindex="0" class="el-upload-list__item is-ready"
                    v-if="img.type=='docx'|img.type=='doc'|img.type=='xls'|img.type=='xlsx'">
                  <div class="demo-image__preview el-upload-list__item-thumbnail">
                    <el-image
                      style="width: 100px; height: 100px"
                      :src="img.fileImgUrl[0]"
                      :preview-src-list="img.fileImgUrl">
                    </el-image>
                    <span class="test" @click="fileDonwload(img.url)">
                      <i class="el-icon-download"></i>
                    </span>
                  </div>
                </li>
              </el-tooltip>
              </span>
            </ul>
          </span>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
      <el-col :offset="1" :span="11">
        <el-row class="uplold">
          <el-col :span="24">
            <el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadUrl"
              :http-request="myUpload"
              :on-remove="handleRemove"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :before-upload="beforeUpload"
              multiple
              accept=".xls,.xlsx,.png,.jpg,.jpeg,.doc,.docx,.ppt,.pptx,.rar,.zip"
              :limit="45"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传</el-button>
              <div slot="tip" class="el-upload__tip">支持上传文件类型只能是文档、图片或压缩文件</div>
            </el-upload>
          </el-col>
          <el-col :span="24" class="row">
            <el-card class="box-card" shadow="never">
              <div v-if="imgList.length <= 0" style="text-align: center;font-size: 15px;color: #8c939d">暂无添加任何文件</div>
              <div slot="header" class="clearfix">
                <span>学生附件</span>
                <el-button style="float: right; padding: 3px 0" type="text" @click="refreshFile">刷新预览</el-button>
              </div>
              <!--        图片-->
              <ul class="el-upload-list el-upload-list--picture-card">
          <span v-for="img in imgList">
            <el-tooltip
              class="item"
              effect="light"
              :hide-after="2000"
              :content="img.name"
              placement="bottom-start">
            <li tabindex="0" class="el-upload-list__item is-ready"
                v-if="img.type=='jpg'|img.type=='png'|img.type=='jpeg'">
              <img class="el-upload-list__item-thumbnail" :src="img.url">
              <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="imgCheck(img.url)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span class="el-upload-list__item-delete" @click="imgDonwload(img.url)">
                    <i class="el-icon-download"></i>
                  </span>
              </span>
            </li></el-tooltip>
          </span>
              </ul>
              <!--        文件file-->
              <span class="file_card">
            <ul class="el-upload-list el-upload-list--picture-card">
            <span v-for="img in imgList">
              <el-tooltip
                class="item"
                effect="dark"
                :hide-after="2000"
                :content="img.name"
                placement="bottom-start">
                <li tabindex="0" class="el-upload-list__item is-ready"
                    v-if="img.type=='docx'|img.type=='doc'|img.type=='xls'|img.type=='xlsx'">
                  <div class="demo-image__preview el-upload-list__item-thumbnail">
                    <el-image
                      style="width: 100px; height: 100px"
                      :src="img.fileImgUrl[0]"
                      :preview-src-list="img.fileImgUrl">
                    </el-image>
                    <span class="test" @click="fileDonwload(img.url)">
                      <i class="el-icon-download"></i>
                    </span>
                  </div>
                </li>
              </el-tooltip>
            </span>
          </ul>
          </span>

              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-card>
            <el-form ref="form" :model="form" label-width="80px" label-position="top" style="margin-top: 10px">
              <el-form-item label="备注：">
                <el-input type="textarea" v-model="form.desc"></el-input>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </el-row>
</template>

<script>
    export default {
        name: "PublishTask",
        data() {
            return {
                userinfo: this.UserInfo.getUserInfo(),
                title_content: "提交内容：" + JSON.parse(decodeURIComponent(this.$route.query.id)).content + " ——— 要求：" + JSON.parse(decodeURIComponent(this.$route.query.id)).ask + "",
                saveLoading: false,
                tea_id: this.UserInfo.getUserInfo().id,
                fileList: [],
                uploadUrl: this.URL.api + "upload/file",//this.URL.api +
                UploadFileList: "",
                dialogImageUrl: '',
                dialogVisible: false,
                disabled: false,
                TimgList: [],
                imgList: [],
                imgList2: [
                    {"type": "img", "fileName": "sdkfsjdfk.jpg", "url": ["http://132.232.47.31:8080/image/w1.jpg"]},
                    {
                        "type": "file",
                        "url": ["http://132.232.47.31:8080/image/w1.jpg", "http://132.232.47.31:8080/image/w2.jpg"]
                    },
                    {"type": "img", "url": ["http://132.232.47.31:8080/image/w1.jpg"]},
                    {
                        "type": "file",
                        "url": ["http://132.232.47.31:8080/image/w1.jpg", "http://132.232.47.31:8080/image/w2.jpg"]
                    }
                ],
                LookFlag: "add",
                form: {
                    desc: ""
                },
                stuFileList: [],
                allData: [],
                listType: [
                    'xls',
                    'xlsx',
                    'png',
                    'jpg',
                    'jpeg',
                    'doc',
                    'docx',
                    'ppt',
                    'pptx',
                    'rar',
                    'zip',
                ],
            }
        },
        methods: {
            goBack() {
                console.log('go back');
                this.$router.go(-1)
                //this.$router.push({name: 'addTopic', params: {act: "3"}});
            },
            MyMessage(msg, type) {
                this.$message({
                    message: msg,
                    type: type
                });
            },
            imgDonwload: function (img) {
                console.log("imgDonwload:" + img);
                window.location.href = this.URL.api + "upload/testDownload?file=" + img;
            },
            fileDonwload(img) {
                console.log("fileDonwload:" + img)
                window.location.href = img;
            },
            imgCheck(img) {
                console.log("imgCheck:" + img)
                this.dialogImageUrl = img;
                this.dialogVisible = true;
            },
            submitForm() {
                console.log(this.userinfo.id)
                console.log(this.allData.teaId)
                console.log(this.allData.id)
                console.log(this.form.desc)
                console.log(this.stuFileList)
                var body = {
                    stuId: this.userinfo.id,
                    teaId: this.allData.teaId,
                    taskId: this.allData.id,
                    stuRemarks: this.form.desc,
                    stuUpFile: this.stuFileList,
                }
                if (this.stuFileList.length <= 0) {
                    this.MyMessage("没有上传任何文件！！！", "warning");
                } else {
                    var self = this;
                    self.$http.post(self.URL.api + "studentsDoTasks/stuAddTask", self.qs.stringify(body))
                        .then(function (response) {
                            console.log(response.data.data)
                            if (response.data.flag) {
                                self.MyMessage("提交成功！！！", "success");
                                self.goBack();
                            } else {
                                self.MyMessage("提交失败，请稍后再试！", "warning");
                            }
                        })
                        .catch(function (error) {
                            self.MyMessage("提交失败，请稍后再试！", "warning");
                        });
                }
            },
            selAllFileImg1() {
                var self = this;
                self.$http.post(self.URL.api + "upload/selFileUrlByTaskId", self.qs.stringify({
                    userId: this.allData.teaId,
                    taskId: this.allData.id
                }))
                    .then(function (response) {
                        console.log(response.data.data)
                        self.TimgList = response.data.data
                    })
                    .catch(function (error) {

                    });
            },
            submitUpload() {
                this.$refs.upload.submit();
            },
            myUpload(content) {
                console.dir(content)
                let formData = new FormData();
                formData.append('file', content.file);
                formData.append('userId', this.userinfo.id);
                this.$http.post(content.action, formData, {
                    headers: {
                        "Content-Type": "multipart/form-data"
                    },
                    onUploadProgress: progressEvent => {
                        let percent = (progressEvent.loaded / progressEvent.total * 99) | 0
                        content.onProgress({percent: percent})
                    }
                }).then((res) => {
                    if (res.data.flag) {
                        content.onSuccess(res.data)
                    } else {
                        content.onError(res.data)
                    }
                }).catch((err) => {
                    content.onError()
                });
            },
            deleteFile(url, id) {
                this.$http.post(this.URL.api + 'upload/deleteFile',
                    this.qs.stringify({fileurl: url}))
                    .then(re => {
                        this.selAllFileImg();
                        //this.UploadFileList=this.UploadFileList.replace(new RegExp(";"+id,'g'),'');
                    });
            },
            handleRemove(file, fileList) {
                if (file.response == undefined) {
                    this.deleteFile(file.url, file.fileId)
                } else {
                    this.deleteFile(file.response.data.url, file.response.data.id)
                }
            },
            uploadSuccess(response, file, fileList) {
                if (file.response.flag) {
                    //this.UploadFileList = this.UploadFileList + ";" + file.response.data.id
                    this.selAllFileImg()
                    console.log(response.data)
                }
            },
            uploadError(err, file, fileList) {
                //console.log(err)
                console.log("失败")
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 15 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
            },
            allFileDown() {
                window.location.href = this.URL.api + "upload/Downloadbatch/"
                    + this.allData.teaId + "/"
                    + this.allData.id +
                    "/" + "任务附件"
            },
            selAllFileImg: function () {
                var self = this;
                self.$http.post(self.URL.api + "upload/selAllFileUrlByUserId", self.qs.stringify({
                    userId: this.userinfo.id,
                    taskId: self.LookFlag
                }))
                    .then(function (response) {
                        console.log(response)
                        self.imgList = response.data.data
                        self.stuFileList = [];
                        self.imgList.forEach(re => {
                            self.stuFileList.push(re.fileId);
                        })
                        console.log(self.stuFileList)
                    })
                    .catch(function (error) {

                    });

            },
            delFile: function () {
                var self = this;
                self.$http.post(self.URL.api + "upload/delFile", self.qs.stringify({
                    userId: this.userinfo.id,
                })).then(function (response) {

                }).catch(function (error) {

                });
            },
            refreshFile() {
                this.selAllFileImg();
            },
            beforeUpload(file) {
                console.log(file)
                var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
                var extension1 = false;
                this.listType.forEach(re => {
                    if (testmsg == re)
                        extension1 = true;
                })
                if (!extension1) {
                    this.$message({
                        message: '上传文件类型只能是文档、图片或压缩文件!',
                        type: 'warning'
                    });
                }
                return extension1;
            },
        },
        mounted: function () { //mounted　表示这个 Vue 对象加载成功了

            // ask:"撒地方撒的"
            // content : "撒旦发射点,   任务书"
            // enclosure : null
            // id :  "1198520934714163200"
            // releaseDate : "2019-11-25 09:20:53"
            // state  : "1"
            // stopDate : "2020-11-12 00:00:00"
            // teaId  : "1195999384584642560"
            // topic : null
            // topicId : "1197398960480747520"
            // type  : "项目开题"

            this.allData = JSON.parse(decodeURIComponent(this.$route.query.id));
            if (this.allData.id == undefined) {
                this.goBack();
            } else {
                // this.data = this.$route.query.id;
                console.log(this.allData);
                this.selAllFileImg1();
            }
            this.delFile();
        }
    }
</script>

<style scoped>

  .row >>> .el-divider--horizontal {
    margin: 10px 0;
  }

  .row >>> .el-card__header {
    padding: 8px 24px;
  }

  .row >>> .el-card {
    margin-top: 15px;
  }

  .row >>> .el-upload-list__item {
    width: 100px;
    height: 100px;
  }

  .row >>> .el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  .uplold >>> .el-upload-list__item {
    transition: none;
  }

  .file_card >>> .el-upload-list__item-actions {
    height: 20%;
    font-size: 10px;
  }

  .file_card >>> .el-upload-list__item-thumbnail:hover .test {
    opacity: 1;
  }

  .test {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 20px;
    background: rgba(0, 0, 0, 0.5);
    color: #ffffff;
    opacity: 0;
    text-align: center;
    cursor: pointer;
    font-size: 16px;
    line-height: 20px;
  }

  .content {
    position: absolute;
    bottom: -30px;
    left: 0;
    width: 100%;
    height: 30px;
    background: rgba(0, 0, 0, 0.5);
    color: #ffffff;
    text-align: center;
    cursor: pointer;
    font-size: 16px;
    z-index: 9999;
  }

  .row >>> .el-form-item__label {
    padding: 0px;
  }
</style>
